package com.nageoffer.shortlink.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nageoffer.shortlink.admin.common.constant.RedisCacheConstant;
import com.nageoffer.shortlink.admin.common.convention.exception.ClientException;
import com.nageoffer.shortlink.admin.common.enums.UserErrorCodeEnum;
import com.nageoffer.shortlink.admin.dao.entity.UserDo;
import com.nageoffer.shortlink.admin.dao.mapper.UserMapper;
import com.nageoffer.shortlink.admin.dto.req.UserLoginReqDTO;
import com.nageoffer.shortlink.admin.dto.req.UserRegisterReqDTO;
import com.nageoffer.shortlink.admin.dto.req.UserUpdateReqDTO;
import com.nageoffer.shortlink.admin.dto.resp.UserLoginRespDTO;
import com.nageoffer.shortlink.admin.dto.resp.UserRespDto;
import com.nageoffer.shortlink.admin.service.GroupService;
import com.nageoffer.shortlink.admin.service.UserService;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.core.env.PropertyResolver;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 用户接口实现层
 */
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, UserDo> implements UserService {
    private final RBloomFilter<String> userRegisterCachePenetrationBloomFilter;

    private final RedissonClient redissonClient;

    private final StringRedisTemplate stringRedisTemplate;
    private final PropertyResolver propertyResolver;
    private final GroupService groupService;

    /**
     * 根据用户名查询用户
     * @param username 用户名
     * @return
     */
    @Override
    public UserRespDto getUserByUsername(String username) {

        LambdaQueryWrapper<UserDo> queryWrapper = Wrappers.lambdaQuery(UserDo.class)
                .eq(UserDo::getUsername, username);
        UserDo userDo = baseMapper.selectOne(queryWrapper);
        if (userDo==null){
            throw new ClientException(UserErrorCodeEnum.USER_NULL);
        }
        else {
            UserRespDto result = new UserRespDto();
            BeanUtils.copyProperties(userDo,result);
            return result;
        }

    }

    /**
     * 查询用户名是否存在
     * @param username
     * @return
     */
    @Override
    public Boolean hasUserName(String username) {
        return userRegisterCachePenetrationBloomFilter.contains(username);
    }

    /**
     * 用户注册
     * @param requstParam
     */
    @Override
    public void register(UserRegisterReqDTO requstParam) {
        if (hasUserName(requstParam.getUsername())){
            throw new ClientException(UserErrorCodeEnum.USERNAME_EXIST);
        }
        RLock lock = redissonClient.getLock(RedisCacheConstant.LOCK_USER_REGISTER_KEY+requstParam.getUsername());
        try{
            if (lock.tryLock()) {

                try{
                    int insert =baseMapper.insert(BeanUtil.toBean(requstParam, UserDo.class));
                    if (insert<1){
                        throw new ClientException(UserErrorCodeEnum.USER_SAVE_ERROR);
                    }
                }catch (DuplicateKeyException ex){
                    throw new ClientException(UserErrorCodeEnum.USER_EXIST);
                }

                userRegisterCachePenetrationBloomFilter.add(requstParam.getUsername());

                groupService.saveGroup(requstParam.getUsername(),"默认分组");

                return;
            }
            throw new ClientException(UserErrorCodeEnum.USER_EXIST);
        }finally {
            lock.unlock();
        }

    }

    /**
     * 更新用户
     * @param userUpdateReqDTO 请求参数
     */
    @Override
    public void update(UserUpdateReqDTO userUpdateReqDTO) {
        //TODO 验证用户是否为登录用户
        LambdaUpdateWrapper<UserDo> eq = Wrappers.lambdaUpdate(UserDo.class)
                .eq(UserDo::getUsername, userUpdateReqDTO.getUsername());
        baseMapper.update(BeanUtil.toBean(userUpdateReqDTO,UserDo.class),eq);

    }


    /**
     * 用户登录接口
     * @param userLoginReqDTO
     * @return
     */
    @Override
    public UserLoginRespDTO login(UserLoginReqDTO userLoginReqDTO) {
        LambdaQueryWrapper<UserDo> eq = Wrappers.lambdaQuery(UserDo.class)
                .eq(UserDo::getUsername, userLoginReqDTO.getUsername())
                .eq(UserDo::getPassword, userLoginReqDTO.getPassword())
                .eq(UserDo::getDelFlag, 0);
        UserDo userDo = baseMapper.selectOne(eq);
        if (userDo==null){
            throw new ClientException(UserErrorCodeEnum.USER_NULL);
        }
        Boolean hasLogin = stringRedisTemplate.hasKey("login_" + userLoginReqDTO.getUsername());
        if (hasLogin!=null && hasLogin){
            throw new ClientException("用户已经登录");
        }
        String uuid = UUID.randomUUID().toString();
        stringRedisTemplate.opsForHash().put("login_"+userLoginReqDTO.getUsername(),uuid,JSON.toJSONString(userDo));
        stringRedisTemplate.expire("login_"+userLoginReqDTO.getUsername(),30,TimeUnit.DAYS);
        return new UserLoginRespDTO(uuid);

    }

    /**
     * 检查登录接口
     * @param username
     * @param token
     * @return
     */
    @Override
    public Boolean checkLogin(String username,String token) {
        return stringRedisTemplate.opsForHash().get("login_"+username, token) != null;
    }


    /**
     * 退出登录接口
     * @param username
     * @param token
     */
    @Override
    public void logout(String username, String token) {
        if (checkLogin(username,token)){
            stringRedisTemplate.delete("login_"+username);
            return;
        }
        throw new ClientException("用户token不存在或者用户未登录");

    }

}
